package org.hxd.dept.controller;

import com.sun.org.apache.xpath.internal.operations.Mod;
import org.hxd.dept.service.DeptService;
import org.hxd.pojo.Dept;
import org.hxd.units.PageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/dept")
public class Deptcontroller {
    @Autowired
    DeptService deptService;
    //部门查询
    @RequestMapping("/dept")
    public String dept(@RequestParam(defaultValue = "1") int pageIndex, Dept dept, Model model){
        PageModel pageModel = new PageModel();
        pageModel.setPageIndex(pageIndex);
        //查询总部门记录数
        int rows = deptService.findDeptCount(dept);
        pageModel.setRocordCount(rows);
        List<Dept> depts = deptService.findDept(pageModel,dept.getName());
        model.addAttribute("pageModel",pageModel);
        model.addAttribute("depts",depts);
        model.addAttribute("dept1",dept);
        return "jsp/dept/dept";
    }
    //跳转部门修改信息页面
    @RequestMapping("/findDeptByid")
    public String updateDept(Dept dept,Model model,int pageIndex){
        model.addAttribute("name",dept.getName());
        dept = deptService.findDeptByid(dept.getId());
        model.addAttribute("dept",dept);
        model.addAttribute("pageIndex",pageIndex);
        return "jsp/dept/showUpdateDept";
    }
    //更新部门信息
    @RequestMapping("/updateDept")
    @ResponseBody
    public String updateDept(Dept dept){
        int rows = deptService.modifyDept(dept);
        if(rows > 0) {
            return "OK";
        }else {
            return "FAIL";
        }
    }
    //部门添加
    @RequestMapping("/addDept")
    @ResponseBody
    public Object addDept(Dept dept){
        int rows = deptService.addDept(dept);
        if(rows>0){
            int deptCount = deptService.findDeptCount(null);
            PageModel pageModel = new PageModel();
            pageModel.setRocordCount(deptCount);
            return pageModel.getTotalSize();
        }else{
            return "FAIL";
        }
    }
    //部门删除
    @RequestMapping("/removeDept")
    @ResponseBody
    public String removeDept(Integer[] ids){
        try{
            int rows = deptService.removeDept(ids);
            if(rows == ids.length){
                return "OK";
            }else{
                return "FAIL";
            }
        }catch (DataIntegrityViolationException e){
            return "ERROR";
        }
    }
}
